<template>
    <view class="inventory-statistics-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="库存统计"></page-header>

        <!-- 筛选区域 -->
        <view class="filter-section">
            <view class="filter-row">
                <!-- 仓库选择 -->
                <view class="filter-item">
                    <uni-data-select
                        v-model="filterData.warehouse"
                        :localdata="warehouseOptions"
                        placeholder="所有仓库"
                        :clear="false"
                        @change="onWarehouseChange">
                    </uni-data-select>
                </view>

                <!-- 搜索框 -->
                <view class="search-container">
                    <uni-easyinput
                        v-model="filterData.searchKeyword"
                        placeholder="搜索农资名称"
                        prefixIcon="search"
                        @input="onSearchInput">
                    </uni-easyinput>
                </view>
            </view>
        </view>

        <!-- 分类标签 -->
        <scroll-view class="category-tabs" scroll-x="true" show-scrollbar="false">
            <view class="tabs-container">
                <view
                    v-for="category in categoryList"
                    :key="category.value"
                    class="tab-item"
                    :class="{ active: selectedCategory === category.value }"
                    @click="selectCategory(category.value)">
                    <text class="tab-text">{{ category.text }}</text>
                </view>
            </view>
        </scroll-view>

        <!-- 表格头部 -->
        <view class="table-header">
            <view class="header-cell name-cell">名称</view>
            <view class="header-cell spec-cell">规格</view>
            <view class="header-cell unit-cell">单位</view>
            <view class="header-cell stock-cell">库存数量</view>
        </view>

        <!-- 库存列表 -->
        <view class="inventory-list">
            <view
                v-for="item in inventoryList"
                :key="item.material_id"
                class="inventory-item">
                <view class="item-cell name-cell">{{ item.material_name }}</view>
                <view class="item-cell spec-cell">{{ getSpecificationName(item.spec_id) }}</view>
                <view class="item-cell unit-cell">{{ getUnitName(item.unit) }}</view>
                <view class="item-cell stock-cell">{{ item.quantity }}</view>
            </view>
        </view>

        <!-- 空状态 -->
        <EmptyData v-if="inventoryList.length === 0 && !loading" text="暂无库存数据" />
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { formatDate } from '@/utils/util'
import { mapGetters, mapActions } from 'vuex'
import { getAgriculturalMaterialsByType } from '@/utils/api/warehouse.js'

export default {
    name: 'InventoryStatistics',
    components: {
        PageHeader,
        EmptyData,
    },
    data() {
        return {
            // 筛选数据
            filterData: {
                warehouse: '',
                searchKeyword: '',
            },
            // 选中的分类
            selectedCategory: '',
            // 分类列表
            categoryList: [],
            // 仓库选项
            warehouseOptions: [],
            // 库存数据
            inventoryList: [],
            // 加载状态
            loading: false,
            // 搜索防抖定时器
            searchTimer: null,
        }
    },
    computed: {
        ...mapGetters([
            'getDictByType',
            'getDictLabel',
            'getWarehouseSelectData',
            'getLocationSelectDataByWarehouseId',
        ]),
    },
    onLoad() {
        this.loadData()
    },
    methods: {
        formatDate,
        ...mapActions(['loadDictByType', 'fetchWarehouseData']),

        // 加载数据
        async loadData() {
            try {
                uni.showLoading({ title: '加载数据...' })
                
                // 加载仓库数据
                await this.fetchWarehouseData()
                
                // 设置仓库选项
                this.warehouseOptions = [
                    { value: '', text: '所有仓库' },
                    ...this.getWarehouseSelectData
                ]

                // 加载字典数据
                await this.loadDictByType('spec_unit')

                // 默认选中第一个仓库
                if (this.getWarehouseSelectData && this.getWarehouseSelectData.length > 0) {
                    const firstWarehouse = this.getWarehouseSelectData[0]
                    this.filterData.warehouse = firstWarehouse.value
                    // 触发仓库选择变化，自动加载分类和库存数据
                    this.onWarehouseChange(firstWarehouse.value)
                }

                uni.hideLoading()
            } catch (error) {
                console.error('加载数据失败:', error)
                uni.hideLoading()
                uni.showToast({
                    title: '加载数据失败',
                    icon: 'none',
                })
            }
        },

        // 处理仓库选择变化
        onWarehouseChange(warehouseId) {
            // 清空分类选择
            this.selectedCategory = ''
            
            // 获取该仓库的库位作为分类标签
            const locationData = this.getLocationSelectDataByWarehouseId(warehouseId)
            if (locationData && locationData.length > 0) {
                this.categoryList = locationData
                // 默认选择第一个分类
                if (locationData.length > 0) {
                    this.selectedCategory = locationData[0].value
                    this.loadInventoryData(locationData[0].value)
                }
            } else {
                this.categoryList = []
                this.inventoryList = []
            }
        },

        // 选择分类
        selectCategory(category) {
            this.selectedCategory = category
            this.loadInventoryData(category)
        },

        // 加载库存数据
        async loadInventoryData(locationId) {
            if (!locationId) {
                this.inventoryList = []
                return
            }

            try {
                this.loading = true
                uni.showLoading({ title: '加载库存数据...' })

                const params = {
                    materialType: locationId,
                    pageNo: 1,
                    pageSize: 99
                }

                // 如果有搜索关键词，添加到参数中
                if (this.filterData.searchKeyword) {
                    params.materialName = this.filterData.searchKeyword
                }

                const res = await getAgriculturalMaterialsByType(params)
                console.log('数据')
                console.log(res)
                if (res.code === 0 && res.data && res.data.length > 0) {
                    this.inventoryList = res.data
                } else {
                    this.inventoryList = []
                }

                uni.hideLoading()
            } catch (error) {
                console.error('加载库存数据失败:', error)
                this.inventoryList = []
                uni.hideLoading()
                uni.showToast({
                    title: '加载库存数据失败',
                    icon: 'none',
                })
            } finally {
                this.loading = false
            }
        },

        // 获取规格名称
        getSpecificationName(specId) {
            if (!specId) return '未知规格'

            // 优先使用字典数据
            const dictLabel = this.getDictLabel('spec_unit', specId)
            if (dictLabel && dictLabel !== specId) {
                return dictLabel
            }

            // 默认映射
            const specMap = {
            }
            return specMap[specId] || `规格${specId}` || '未知规格'
        },

        // 获取单位名称
        getUnitName(unit) {
            if (!unit) return '未知单位'
            
            const dictLabel = this.getDictLabel('unit', unit)
            return dictLabel ||'未知单位'
        },

        // 搜索输入处理
        onSearchInput() {
            // 清除之前的定时器
            if (this.searchTimer) {
                clearTimeout(this.searchTimer)
            }
            
            // 设置防抖定时器，500ms后执行搜索
            this.searchTimer = setTimeout(() => {
                // 如果有选中的分类，重新加载数据
                if (this.selectedCategory) {
                    this.loadInventoryData(this.selectedCategory)
                }
            }, 500)
        },
    },
}
</script>

<style lang="scss" scoped>
.inventory-statistics-container {
    min-height: 100vh;
    background-color: #f5f5f5;
}

.filter-section {
    background-color: #fff;
    padding: 20rpx;
    margin-bottom: 20rpx;

    .filter-row {
        display: flex;
        align-items: center;
        gap: 20rpx;
    }

    .filter-item {
        flex: 1;
    }

    .search-container {
        flex: 2;
    }
}

.category-tabs {
    background-color: #fff;
    border-bottom: 1rpx solid #eee;

    /* 隐藏滚动条 */
    ::-webkit-scrollbar {
        display: none;
        width: 0;
        height: 0;
    }

    .tabs-container {
        display: flex;
        padding: 0 20rpx;
        white-space: nowrap;

        /* 兼容性更好的隐藏滚动条方案 */
        scrollbar-width: none; /* Firefox */
        -ms-overflow-style: none; /* IE 10+ */

        &::-webkit-scrollbar {
            display: none; /* Chrome Safari */
            width: 0;
            height: 0;
        }
    }

    .tab-item {
        padding: 30rpx 40rpx;
        position: relative;
        flex-shrink: 0; /* 防止压缩 */
        white-space: nowrap; /* 防止换行 */

        .tab-text {
            font-size: 28rpx;
            color: #666;
            white-space: nowrap; /* 文本不换行 */
        }

        &.active {
            .tab-text {
                color: #4a7c59;
                font-weight: 500;
            }

            &::after {
                content: '';
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translateX(-50%);
                width: 60rpx;
                height: 4rpx;
                background-color: #4a7c59;
                border-radius: 2rpx;
            }
        }
    }
}

.table-header {
    background-color: #f8f9fa;
    display: flex;
    align-items: center;
    padding: 20rpx;
    border-bottom: 1rpx solid #eee;

    .header-cell {
        font-size: 28rpx;
        color: #666;
        font-weight: 500;
        text-align: center;
    }

    .name-cell {
        flex: 2;
        text-align: left;
    }

    .spec-cell {
        flex: 2;
    }

    .unit-cell {
        flex: 1;
    }

    .stock-cell {
        flex: 1.5;
    }
}

.inventory-list {
    background-color: #fff;

    .inventory-item {
        display: flex;
        align-items: center;
        padding: 30rpx 20rpx;
        border-bottom: 1rpx solid #f0f0f0;

        &:last-child {
            border-bottom: none;
        }

        .item-cell {
            font-size: 28rpx;
            color: #333;
            text-align: center;
        }

        .name-cell {
            flex: 2;
            text-align: left;
            font-weight: 500;
        }

        .spec-cell {
            flex: 2;
            color: #666;
        }

        .unit-cell {
            flex: 1;
            color: #666;
        }

        .stock-cell {
            flex: 1.5;
            font-weight: 500;
            color: #4a7c59;
        }
    }
}

.empty-state {
    text-align: center;
    padding: 120rpx 40rpx;
    background-color: #fff;

    .empty-icon {
        font-size: 80rpx;
        margin-bottom: 20rpx;
    }

    .empty-text {
        font-size: 28rpx;
        color: #999;
    }
}
</style>
